﻿(function ($) {
    $.widget('hwschool.onlinechat', {
        options:
        {
            title:'Задать вопрос',
            updatefrequency: 3000,
            staticView: false,
            linkedSessionId: '',
            author: 'Пользователь',
            authorAlias: 'Я',
            adminPanel: false,
            additionalTrigger: null,
            externalHost:''
        },
        requestMsgQuery: null,
        postMgsQuery: null,
        requestSessionQuery: null,
        archiveChatQuery:null,

        _readCookie:function(key){
            return $.cookie(key);
        },

        _getHost:function(){
            return this.options.externalHost;
        },
        _writeCookie:function(key,value,obj){
            $.cookie(key,value,obj);
        },
        deleteCookie:function(key){
            $.removeCookie(key);
        },
        _appendMessage:function(message,preventAnimation){
            this.lastMessageId = message.MessageId;
            var messageItem = $('<div class="message_item">');

            var authorAlias = message.Author;
            if (authorAlias == this.options.author && this.options.authorAlias != '') {
                authorAlias = this.options.authorAlias;
            }


            messageItem.html('<b>' + authorAlias + '</b> ' + message.MessageText + '<hr/>');
            messageItem.appendTo(this.message_body);

            this._scrollDownMessages(preventAnimation);
        },

        _scrollDownMessages:function(preventAnimation){
            var n = $(this.message_body)[0].scrollHeight;

            if (preventAnimation) {
                $(this.message_body).scrollTop(n);
            }
            else {
                $(this.message_body).animate({ scrollTop: n }, '50');
            }
        },
        _setOption: function(key, value) {
            if (key == 'additionalTrigger') {
                this.options['additionalTrigger'] = value;
                this._hookAdditionalTrigger();
            }
        },

        _runNextMessageLoader: function () {
            if (this.stopLooping) {
                return;
            }
            var that = this;
            if (this.chatPanelExpanded) {
                setTimeout(function () {
                    that._loadMessages(false);
                }, that.options.updatefrequency);
            }
            else {
                //setTimeout(function () {
                //    that._runNextMessageLoader();
                //}, that.options.updatefrequency * 2);
            }
        },
        _clearInput:function(){
            this.enterTextArea.val('');
        },
        _sendMessage: function () {
            if (this.isSending)
                return;

            if (this.enterTextArea.val().trim().length == 0)
                return;

            this.isSending = true;

            var that    = this;
            var msg     = this.enterTextArea.val();

            var request = {
                SessionId: this.sessionID,
                LastMessageId: this.lastMessageId,
                Author:this.options.author,
                Message:msg.trim()
            };

            if (msg && msg.length > 0 && msg.trim().length > 0) {
                this.postMgsQuery = $.post(this._getHost() + '/api/OnlineMessenger',request)
                    .done(function (result) {
                        if (result && result.MessageId - that.lastMessageId == 1) {
                            //we know that the posted message is exactly the next message in the sequence 
                            that.skipLastReloadCycle = true;
                            that._appendMessage(result, false, true);
                        }
                        that.isSending = false;
                    })
                    .error(function () {
                        result =
                            {
                                MessageId: that.lastMessageId,
                                Author:'Ошибка доставки',
                                MessageText:'Ваше сообщение не доставлено'
                            }
                        that._appendMessage(result, false, true);
                        that.isSending = false;
                    });
                this._clearInput();
            }
        },

        _loadMessages:function(preventAnimation){
            var request = {
                SessionId    : this.sessionID,
                LastMessageId: this.lastMessageId
            };
            var that = this;

            this.requestMsgQuery = $.get(this._getHost() + '/api/OnlineMessenger/MeetingMessages', { sessionVM: request })
                 .done(function (data) {
                     if (that.skipLastReloadCycle) {
                         //console.log('message loading result has been skipped');
                         that.skipLastReloadCycle = false;
                         that._runNextMessageLoader();
                         return;
                     }

                     if ($(data).length > 0) {
                         //new messages have сame
                         $.each(data, function (idx,value) {
                             that._appendMessage(value, preventAnimation);
                         });
                     }
                     else {
                         //no new messages were returned 
                     }
                     that._runNextMessageLoader();
                 })
                 .error(function () {
                     var errorText = $.parseJSON(arguments[0].responseText).ExceptionMessage;
                     if (errorText == "Session no longer exists") {
                         that.sessionID = '';
                         if (that.options.linkedSessionId == '') {
                             that._writeCookie('onlineChatSessionId', '', { path: '/',domain:'kharkovitcourses.com'});
                         }
                         if (!this.stopLooping) {
                             that._initChatSession();
                         }
                     }
                     else {
                         that._runNextMessageLoader();
                     }
                 });
        },
        lastMessageId:-1,
        sessionID:'',

        _isIE: function() {
            var myNav = navigator.userAgent.toLowerCase();
            return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
        },
        destroy: function () {
            this.stopLooping = true;
            $.Widget.prototype.destroy.call(this);
        },
        _changeVisibility:function(supressFade){
            var that = this;
            if (this._isIE()) {
                supressFade = true;
            }

            if (this.chatPanelExpanded) {
                this.chatPanelExpanded = false;
                if (supressFade) {
                    this.chatBodyElement.css("display", "none");
                }
                else {
                    this.chatBodyElement.toggle('blind');
                }
                this.expanPanelLink.removeClass('expanded');
                this._writeCookie('chatExpanded', false, { path: '/', domain: 'kharkovitcourses.com' });
            }
            else {
                this.chatPanelExpanded = true;
                if (supressFade) {
                    this.chatBodyElement.css("display", "block");
                }
                else {
                    this.chatBodyElement.toggle('blind', function () {
                        that._scrollDownMessages(true);
                    });
                }
                this.expanPanelLink.addClass('expanded');
                if (!this.options.staticView) {
                    this._writeCookie('chatExpanded', true, { path: '/', domain: 'kharkovitcourses.com' });
                }
                this._initChatSession();
            }
        },
        _initChatSession: function () {
            if (this.stopLooping) {
                return;
            }
            if (this.sessionID != '') {
                this._loadMessages(true);
            }
            else {
                var lastSesion = this.options.linkedSessionId !== '' ? this.options.linkedSessionId : this._readCookie('onlineChatSessionId');
                var that = this;
                this.requestSessionQuery = $.get(this._getHost() + '/api/OnlineMessenger/MeetingSession', { lastSessionId: lastSesion })
                    .done(function (data) {
                        that.lastMessageId = data.LastMessageId;
                        that.sessionID = data.SessionId;
                        if (that.options.linkedSessionId == '') {
                            that._writeCookie('onlineChatSessionId', that.sessionID, { path: '/', domain: 'kharkovitcourses.com' });
                        }
                        that.message_body.empty();
                        that._loadMessages(true);
                    });
            }
        },
        _archiveChat: function () {
            var that = this; 
            this.stopLooping = true;
            this.archiveChatQuery = $.post(this._getHost() + '/api/OnlineMessenger/ArchiveSession', '=' + this.sessionID)
                                .success(function () {
                                    that._trigger('dialogclosed', that, that.sessionID);
                                })
                                .error(function () {
                                });
        },

        _hookAdditionalTrigger: function () {
            var that = this;
            if (this.options.additionalTrigger) {
                this.options.additionalTrigger.bind('click', function () {
                    that.wrapperElement.fadeIn();
                    if (that.chatPanelExpanded) {
                        var options = {};
                        that.wrapperElement.effect('bounce',options, 500);
                    }
                    else {
                        that._changeVisibility();
                    }
                });
            }
        },
        _beforeUnload: function (e) {
            try
            {
                if (this.requestMsgQuery){
                    this.requestMsgQuery.abort();
                }
                if (this.postMgsQuery){
                    this.postMgsQuery.abort();
                }
                if (this.requestSessionQuery){
                    this.requestSessionQuery.abort();
                }
                if (this.archiveChatQuery){
                    this.archiveChatQuery.abort();
                }
            }
            catch (exception)
            {
            }
        },

        _create: function () {
          
            var buttonsWrapperDiv = $('<div class="chatHeaderButtons">');
            var chatTextHeader = $('<div class="chatTextHeader">');
            var chatText       = $('<div class="chatText">');
            var chatInput = $('<div class="chatInput">');

            var message_area = $('<div class="message_area">');
            this.message_body = $('<div class="message_body">');
            var message_item = $('<div class="message_item">');

            var that = this;

            $(window).bind('beforeunload', function (e) {
                that._beforeUnload(e);
            });


            this.wrapperElement = $('<div class="chatWrapper">');
            this.chatHeaderElement = $('<div class="chatHeader">');
            this.chatBodyElement = $('<div class="chatBody">');
            this.expanPanelLink = $('<div class="expandChatPanelLink">');
            this.closePanelLink = $('<div class="closePanelLink">');
            this.archivePanelLink = $('<div class="archivePanelLink">');
            this.chatIconPanelElmenet = $('<div class="chatIcon">');
            this.headerTextElement    = $('<div class="headerCaption">');

            this.enterTextArea = $('<textarea class="message_input"></textarea>');
            this.sendTextButton = $('<input class="message_send" type="button" value="отправить">');

            this.enterTextArea.appendTo(chatInput);
            this.sendTextButton.appendTo(chatInput);

            this.chatIconPanelElmenet.appendTo(buttonsWrapperDiv);
            this.headerTextElement.appendTo(buttonsWrapperDiv);

            if (!this.options.staticView) {
                this.closePanelLink.appendTo(buttonsWrapperDiv);
                this.expanPanelLink.appendTo(buttonsWrapperDiv);
            }

            if (this.options.adminPanel) {
                this.archivePanelLink.appendTo(buttonsWrapperDiv);
            }

            this.headerTextElement.text(this.options.title);

            this.chatHeaderElement.appendTo(this.wrapperElement);
            buttonsWrapperDiv.appendTo(this.chatHeaderElement);
            this.chatBodyElement.appendTo(this.wrapperElement);

            message_area.appendTo(chatText);
            this.message_body.appendTo(message_area);

            chatTextHeader.appendTo(this.chatBodyElement);
            chatText.appendTo(this.chatBodyElement);
            chatInput.appendTo(this.chatBodyElement);

            this.wrapperElement.appendTo(this.element);

            this._hookAdditionalTrigger();

            this.closePanelLink.bind('click', function () {
                that._writeCookie('chatExpanded', false, { path: '/', domain: 'kharkovitcourses.com'});
                that.wrapperElement.fadeOut();
                //that.destroy();
            });

            this.archivePanelLink.bind('click', function () {
                $("<p>Вы действительно хотите переместить разговор в архив?</p>").dialog({
                    resizable: false,
                    dialogClass: 'noTitleStuff',
                    height: 150,
                    modal: true,
                    buttons: {
                        "Удалить": function () {
                            that._archiveChat();
                            $(this).dialog("close");
                        },
                        "Отмена": function () {
                            $(this).dialog("close");
                        }
                    }
                });

            });

            this.expanPanelLink.bind('click',function(){
                that._changeVisibility();
            });

            this.chatIconPanelElmenet.bind('click',function(){
                that._changeVisibility();
            });

            this.enterTextArea.keyup(function (event) {
                if (event.keyCode == 13) {
                    that._sendMessage();
                }
                else if (event.keyCode == 27) {
                    that._clearInput();
                }
            });


            var lastPanelState = this._readCookie('chatExpanded');
            if (this.options.staticView || (lastPanelState && lastPanelState == 'true')) {
                this._changeVisibility(true);
            }
        }
    });
})(jQuery);